package cn.cnlee.tv.airport.service;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

/***
 * 这个类就是在运行的小型服务器了。serve方法用于获取客户端请求的数据，和返回请求结果。
 */
public class HttpServer extends NanoHTTPD {

    public static final String TAG = HttpServer.class.getSimpleName();
    public static final int DEFAULT_SERVER_PORT = 8088;
    public Context mContext;

    public HttpServer(Context context, int port) {
        super(port);
        this.mContext = context;
    }

    //当接受到连接时会调用此方法
    @Override
    public Response serve(IHTTPSession session) {
        Map<String, String> header = session.getHeaders();
        Map<String, String> params = session.getParms();
        Method method = session.getMethod();
        String url = params.get("url");
        String uri = session.getUri();
        Log.d(TAG, "uri : " + uri);
        Log.d(TAG, "url : " + url);
        String responseTxt;
        if (!TextUtils.isEmpty(uri) && "/airport".equals(uri)) {
            responseTxt = loadLocalHtml(this.mContext);
        } else {
            /*我在这里做了一个限制，只接受POST请求。这个是项目需求。*/
            if (Method.POST.equals(method)) {
                Log.e(TAG, "POST方法");
                Map<String, String> files = new HashMap<>();
                /*获取header信息，NanoHttp的header不仅仅是HTTP的header，还包括其他信息。*/
                try {
                    /*这句尤为重要就是将将body的数据写入files中，大家可以看看parseBody具体实现，倒现在我也不明白为啥这样写。*/
                    session.parseBody(files);
                    /*看就是这里，POST请教的body数据可以完整读出*/
                    String body = session.getQueryParameterString();//
                    Log.d(TAG, "header : " + header);//
                    Log.d(TAG, "body : " + body);
                    /*这里是从header里面获取客户端的IP地址。NanoHttpd的header包含的东西不止是HTTP heaer的内容*/
                    header.get("http-client-ip");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (Method.GET.equals(method)) {
                Log.e(TAG, "GET方法");
            }
            responseTxt = String.format("方式：%s<br/>网址：%s<br/>TV上已经打开！", method, url);
            try {
                openBrowser(this.mContext, url);
            } catch (Exception e) {
                responseTxt = String.format("方式：%s<br/>网址：%s<br/>打开网址失败！", method, url);
            }finally {
                responseTxt = "<!DOCTYPE HTML><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1,minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\" /><title>云联</title><style type=\"text/css\">html,body,p,form,div,table,textarea,input,span,select{font:normal 100% Helvetica,Arial,sans-serif;word-wrap:break-word}body{background:#fff;color:#000;padding:1px;margin:1px}body,div,ul,ol,li,h1,h2,h3,h4,h5,h6,form,input,textarea,dd,dt,p{margin:0;padding:0}form{margin:0;padding:0;border:0}a{color:#222;text-decoration:none;outline:0;blr:expression(this.onFocus=this.blur())}.header{background-color:#009af7;min-height:2.9rem;position:relative;clear:both}.title{color:#fff;font-size:1.2rem;font-weight:normal;margin:0 auto;line-height:2.9rem;text-align:center;text-overflow:ellipsis;white-space:nowrap;width:15rem}</style></head><body><div class=\"header\"><h2 class=\"title\">云联</h2></div><div style=\"padding: 20px;\">" + responseTxt + "</div></body>";
            }
        }
        return newFixedLengthResponse(Response.Status.OK, "text/html", responseTxt);
    }

    private String loadLocalHtml(Context context) {

        InputStreamReader inputStreamReader = null;
        try {
            InputStream inputStream = context.getAssets().open("airport.html");
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private void openBrowser(Context context, String url) throws Exception {
        if (TextUtils.isEmpty(url)) return;
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}